import Vue from 'vue'
import Vuex from 'vuex'
import _config from '@/config/index.js'; // 导入私有配置
Vue.use(Vuex)
import audio from '@/store/modules/audio.js';

const store = new Vuex.Store({
	modules:{
		audio
	},
	state: {
		CONNECT : 1,// 第一次(或重连)初始化连接
		CHAT : 2,// 聊天消息
		SIGNED : 3,// 消息签收
	    KEEPALIVE : 4,	// 客户端保持心跳
		PULL_FRIEND : 5,
		user: null,
		navHeight:0,
		avatar:'',
		socketTask: null,
		isInit:false,
		INTERVAL:"",
		eventlist: []
	},
	mutations: {
		WEBSOCKET_INIT(state) {
			console.log("Websocket初始化")
			if(state.socketTask!=null&&state.socketTask !=undefined&&state.socketTask.readyState==1){
				return false;
			}
			state.socketTask = uni.connectSocket({
				url: _config.nettyServerUrl,
				success(data) {
					console.log("websocket连接成功");
				},
			});
			var that = this;
			// 消息的发送和接收必须在正常连接打开中,才能发送或接收【否则会失败】
			state.socketTask.onOpen(function(){
				uni.setStorageSync("isConnect",true)
				console.log("websocket连接已建立...");
				var me =uni.getStorageSync("userInfo");
				var phone = me.PHONE
				if(me.LOGIN_ROLE!=1){
					phone = me.PHONE+'med'
				}
				// 构建ChatMsg
				var chatMsg ={
					username:phone,
					senderId:uni.getStorageSync("userId"),
					receiverId:null,
					msg:null,
					msgId:null,
					msgType:"0"
				}
				// 构建DataContent
				var dataContent ={
					action:state.CONNECT,
					chatMsg:chatMsg,
					extand:null
				}
				// 发送websocket
				that.commit('WEBSOCKET_SEND',dataContent)
				state.isInit = true
				
				// 每次连接之后，获取用户的未读未签收消息列表
				that.commit('fetchUnReadMsg')
				
				clearInterval(state.INTERVAL)
				
				// 定时发送心跳
				state.INTERVAL = setInterval(function(res){
					// 构建对象
					var dataContent ={
						action:state.KEEPALIVE,
						chatMsg:null,
						extand:null
					}
					// 发送心跳
					if(state.isInit == true){
						that.commit('WEBSOCKET_SEND',dataContent)
					}
				},10000)
			})
			state.socketTask.onMessage(function(e){
				var chatMsg = JSON.parse(e.data).chatMsg;
				var user = uni.getStorageSync("userInfo")
				var myUsername = user.PHONE
				if(user.LOGIN_ROLE!=1){
					myUsername = user.PHONE+'med'
				}
				
				var myName = user.NAME
				var username = chatMsg.username;
				var name = chatMsg.nickname;
				var avatar = chatMsg.faceimage;
				var list = uni.getStorageSync(myUsername+username)||[];
				var msg = {
					"from_id":username,
					"create_time":new Date(chatMsg.createTime.replace(/-/g,  "/")).getTime(),				
					"msg_type":chatMsg.msgType,
					"msg_body":chatMsg.msg,
					"msg_id":chatMsg.msgId,
					"extra":chatMsg.extra!=null?JSON.parse(chatMsg.extra):null
				}
				var text='';
				switch(Number(chatMsg.msgType)){
					case 0:
						text = chatMsg.msg;
						break;
					case 1:
						text = '[图片]';
						break;
					case 2:
						text = '[语音]'
						break;
					case 3:
						text = '[短视频]'
						break;
					case 4:
						text = '[表情]'
						break;
				}
				var data = {
					"request_id":String(new Date().getTime())+Math.ceil(Math.random()*1000),
					"audience":{
					  "cid":[
						  uni.getStorageSync("cid")
					  ]
					},
					"push_message":{
					  "notification":{
						  "title":name,
						  "body":text,
						  "channel_level":4,
						  "click_type":"payload",
						  "payload":JSON.stringify({
							  'nickname':name,
							  'username':username,
							  'avatar':avatar
						  })
					  }
					}
			   }
				uni.request({
					url:`https://restapi.getui.com/v2/${_config.appid}/push/single/cid`,
					method:"POST",
					header:{
						'ContentType':"application/json;charset=utf-8",
						'token':uni.getStorageSync("unipushToken")
					},
					data:data,
					success(res) {
					},
					fail(res){
					}
				})
				var count = uni.getStorageSync(username)||0
				count++;
				uni.setStorageSync(username,count)
				uni.showTabBarRedDot({
					index:1
				})
				list.push(msg);
				uni.setStorageSync(myUsername+username,list)
				var music = null;
				music = uni.createInnerAudioContext(); //创建播放器对象
				music.src= "/static/audio/message.mp3"; //选择播放的音频
				music.play(); //执行播放
				//消息来了震动
				uni.vibrateLong({
					success: function () {
					}
				});
				that.commit("signMsgList",","+chatMsg.msgId+",")
				uni.$emit('get_chat_msg',{})
				uni.$emit('get_unread',{})
			})
			state.socketTask.onClose(function(e){
				state.isInit = false
				uni.setStorageSync("isConnect",false)
				console.log("连接关闭...");
			})
			state.socketTask.onError(function(e){
				uni.setStorageSync("isConnect",false)
				uni.showToast({
					"title":"网络连接不可用",
					"position":"bottom",
					"icon":"none"
				})
			})
			
		},
		WEBSOCKET_SEND(state, msg) {
			msg = JSON.stringify(msg)
			if (state.socketTask != null && state.socketTask != undefined &&state.socketTask.readyState == 1) {
				state.socketTask.send({
					data:msg,
					success(res){
					},
					fail(res){
						
					}
				})
			} else {
				// 重连websocket
				this.commit('WEBSOCKET_INIT')
				this.commit('WEBSOCKET_RECHAT',msg)
			}
		},
		WEBSOCKET_RECHAT(state,msg){
			setTimeout(function(){
				state.socketTask.send({
					data:msg
				});
			},1000)
			
		},
		signMsgList(state,unSignedMsgIds){
			var dataContent ={
				action:state.SIGNED,
				chatMsg:null,
				extand:unSignedMsgIds
			}
			this.commit('WEBSOCKET_SEND',dataContent)
		},
		fetchUnReadMsg(state){
			var user = uni.getStorageSync("userInfo")
			var msgIds = ","
			var _this = this;
			var phone = user.PHONE
			if(user.LOGIN_ROLE !=1){
				phone = phone+'med'
			}
			uni.request({
				url:_config.serverUrl +"/u/getUnReadMsgList?username=" + phone,
				method:"post",
				success(res){
					var chatList = res.data.data
					if(chatList.length!=0){
						var myUsername = user.PHONE
						if(user.LOGIN_ROLE !=1){
							myUsername = myUsername+'med'
						}
						uni.showTabBarRedDot({
							index:1
						})
						for(var i=0;i<chatList.length;i++){
							var username = chatList[i].username;
							var list = uni.getStorageSync(myUsername+username)||[];
							var count = uni.getStorageSync(username)||0
							var msg = {
								"from_id":username,
								"create_time":new Date(chatList[i].createTime.replace(/-/g,  "/")).getTime(),				
								"msg_type":chatList[i].msgType,
								"msg_body":chatList[i].msg,
								"msg_id":chatList[i].msg_id,
								"extra":chatList[i].extra!=null?JSON.parse(chatList[i].extra):null
							}
							msgIds +=chatList[i].id;
							msgIds +=","
							list.push(msg);
							count++
							uni.setStorageSync(username,count)
							uni.setStorageSync(myUsername+username,list)
						}
						_this.commit("signMsgList",msgIds)
					}
				}
			})
		},
		setuser(state, user) {
			state.user = user
		},
		login(state, user) {
			state.user = user
			// 缓存用户信息
			uni.setStorageSync("userInfo",user)
		},
		logout(state,flag=true) {
			state.user = null
			// 清理缓存用户信息
			uni.closeSocket()
			uni.setStorageSync("userDisconnect",flag)
			uni.removeStorageSync("location")
			uni.removeStorageSync("heart")
			uni.removeStorageSync("blood")
			uni.removeStorageSync("sleep")
			uni.removeStorageSync("temperature")
			uni.removeStorageSync("bloodOxygen")
			uni.removeStorageSync("respiratoryRate")
			uni.removeStorageSync("autoInfo")
			uni.removeStorageSync("followInfo")
			uni.removeStorageSync("followNum")
			uni.removeStorageSync("loginInfo")
			uni.removeStorageSync("loginShowcount")
			uni.removeStorageSync("role")
			uni.removeStorageSync("userId")
			uni.removeStorageSync("userInfo")
			uni.removeStorageSync("isToggle")
		}
	},
	actions: {
		WEBSOCKET_INIT({
			commit
		}) {
			commit('WEBSOCKET_INIT')
		},
		WEBSOCKET_SEND({
			commit
		},msg) {
			commit('WEBSOCKET_SEND', msg)
		},
		login({
			commit
		}, params) {
			return new Promise((resolve, reject) => {
				 // api请求
				 //增加是否是医护一键切换的普通用户标识
				 params.flag=uni.getStorageSync("isToggle")||false
				 Vue.prototype.$http.login(params).then(data=>{
					 resolve(data)
					 if (data.code == 1) {
						commit('login', data.result)
					 }
				 }).catch(err => {
					reject(err)
				 })
			})
		},
		logout({
			commit
		},flag) {
			commit('logout',flag)
		},
		register({commit}, params) {
			return new Promise((resolve, reject) => {
				 // * api请求
				 Vue.prototype.$http.register(params).then(data => {
					 resolve(data)
					 commit('setuser', params)
				}).catch(err => {
					reject(err)
				})
			})
		}
	},
	getters: {
		user: state => {
			return uni.getStorageSync("userInfo")
		},
		navHeight:state=>{
			return (Vue.prototype.StatusBar+uni.upx2px(100))+'px';
		},
		avatar:state=>{
			var userInfo = uni.getStorageSync("userInfo");
			return userInfo.AVATAR?userInfo.AVATAR:_config.NGINX_SERVER+'imgs/avatar/avatar.jpg'
		}
	}
})

export default store
